package com.pzhu.servlet;

import com.pzhu.controller.UserController;
import com.pzhu.controller.impl.UserControllerImpl;
import com.pzhu.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class RegisterServlet extends HttpServlet {
    private UserController userController = new UserControllerImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        user.setId(Long.parseLong((req.getParameter("id"))));
        user.setAccount(Long.parseLong(req.getParameter("id")));
        user.setName(req.getParameter("username"));
        user.setPassword(req.getParameter("password"));
        if (req.getParameter("sex").equals("男"))
            user.setSex(true);
        user.setAcademy("数学与计算机学院");
        user.setProfession(req.getParameter("profession"));
        user.setClasses(req.getParameter("classes"));
        SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");

        try {
            user.setBirthday(ft.parse(req.getParameter("birthday")));
            user.setEnrollment((ft.parse(req.getParameter("enrollment"))));
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        boolean b = userController.addUser(user);
        if (b) {
            req.setAttribute("msg","注册成功");
            req.getRequestDispatcher("main").forward(req, resp);
            return;
        }else {
            req.setAttribute("msg","注册失败");
            req.getRequestDispatcher("/view/jsp/register.jsp").forward(req, resp);
        }
    }
}
